var $clicksearch = $(".clicksearch")
var $input = $(".shousuo>input")
var $box = $(".box")
var $list = $(".list")
var $getFriendlist = $(".getFriendlist")
var $myFriendlist = $(".myFriendlist")
var $searchlist = $(".search-list")
var searchData;
var friend;
var $main = $(".main")
var time;
var id;
var nick;
var $forword
var $logo = $(".logo");
var userData = JSON.parse(localStorage['userData']);
// console.log(userData.head_logo)
$logo.html(`<img src="http://118.24.25.7/chat_api${userData.head_logo}">`)
//搜索好友
$clicksearch.on('click', function () {
    // console.log(111)
    searchData = {
        sign_str: localStorage.getItem('sign_str'),
        user_id: localStorage.getItem('user_id'),
        search_text: $input.val()
    }
    // console.log(searchData)
    $.ajax({
        type: "get",  //数据提交方式（post/get）
        url: "http://118.24.25.7/chat_api/interface/getSearchUsers.php",  //提交到的url
        data: searchData,//提交的数据
        dataType: "json",//返回的数据类型格式
        success: function (rel) {
            friend = rel.data[0].id
            if (rel.code == 0) {
                var str = "";
                for (var i = 0; i < rel.data.length; i++) {
                    str += `
                    <div class="list-item">
                        <img src="http://118.24.25.7/chat_api/${rel.data[i].head_logo}">
                        <span>${rel.data[i].nickname}</span>
                        <div class="add">添加</div>
                    </div>
                    `

                }
                $searchlist.html(str)
            }
        }
    })
})

//添加好友
var $add = $(".add")
// console.log($add)
$list.on("click", ".add", function () {

    var addData = {
        sign_str: localStorage.getItem('sign_str'),
        user_id: localStorage.getItem('user_id'),
        friend_user_id: friend,
    }
    // console.log(addData)
    $.ajax({
        type: "post",  //数据提交方式（post/get）
        url: "http://118.24.25.7/chat_api/interface/addFriend.php", //提交到的url
        data: addData,//提交的数据
        dataType: "json",//返回的数据类型格式
        success: function (rel) {
            console.log(rel)
            if (rel.code == 0) {
                // alert("好友申请成功，请等待对方确认")
                var str = `
                <div class="tooltips">
                    <div class="tooltips-title">
                        好友申请成功，请等待对方确认。
                    </div>
                </div>`
                $box.append(str)
                var $tooltips = $(".tooltips")
                time = setTimeout(function () {
                    $tooltips.css("display", "none")
                    window.location.reload()
                    clearTimeout(time)
                }, 1200)

            } else {
                alert("好友申请失败")
            }
        }
    });
})


// 获取好友申请
var requestid = null;
function clx() {

    // console.log(userData)
    var getFriendRquest = {
        sign_str: localStorage.getItem('sign_str'),
        user_id: localStorage.getItem('user_id')
    }
    // console.log(getFriendRquest)
    $.ajax({
        type: "get",
        url: " http://118.24.25.7/chat_api/interface/getFriendRequests.php",
        data: getFriendRquest,
        dataType: "json",
        timeout: 2000,
        success: function (res) {
            // console.log("success", res)
            if (res.data[0].request_id == requestid) {
                return;
            } else {
                requestid = res.data[0].request_id
            }
            if (res.code == 0) {
                console.log("success", res)
                for (var i = 0; i < res.data.length; i++) {

                    var str = `
                <div class="list-item">
                    <img src="http://118.24.25.7/chat_api/${res.data[i].head_logo}">
                    <span>
                    ${res.data[i].nickname}
                    </span>
                    <div class="conset" data-userid="${res.data[i].user_id}" data-reqid="${res.data[i].request_id}">接受</div>
                </div>
                `
                    $getFriendlist.append(str)
                }
            }
        },
        error: function (err) {
            console.log(err)
        },
        complete: function () {
            clx()
        }
    });
}
clx();
//处理好友申请

// var $conset = $(".conset")
$list.on("click", ".conset", function () {
    var disposeData = {
        sign_str: userData.sign_str,
        user_id: userData.user_id,
        from_user_id: this.dataset.userid,
        request_id: this.dataset.reqid,
        process_result: 1
    }
    $.ajax({
        type: "post",
        url: "http://118.24.25.7/chat_api/interface/processFriendRequest.php",
        data: disposeData,
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                var str = `
                <div class="tooltips">
                    <div class="tooltips-title">
                        已成功添加对方为好友。
                    </div>
                </div>`
                $box.append(str)
                var $tooltips = $(".tooltips")
                time = setTimeout(function () {
                    $tooltips.css("display", "none")
                    window.location.reload()
                    clearTimeout(time)
                }, 1200)


            }
        }
    })

    // console.log(disposeData)
})



//获取好友列表

$.ajax({
    type: "get",
    url: "http://118.24.25.7/chat_api/interface/getFriends.php",
    data: userData,
    dataType: "json",
    success: function (res) {
        if (res.code == 0) {
            for (var i = 0; i < res.data.length; i++) {
                console.log(res.data)
                var str = `
                <div class="list-item">
                    <img src="http://118.24.25.7/chat_api/${res.data[i].head_logo}">
                    <span>
                    ${res.data[i].nickname}
                    </span>
                    <div class="active" style="background-color :${res.data[i].online == 1 ? 'green' : 'red'};"></div>
                </div>
                `
                // window.location.reload() //随时刷新页面
                $myFriendlist.append(str)
            }
            $myFriendlist.on("click", ".list-item", function () {
                $(".list-item").eq($(this).index()).addClass("list-item-active").siblings().removeClass("list-item-active")
                nick = res.data[$(this).index()].nickname
                id = res.data[$(this).index()].user_id
                var fridentlogo = res.data[$(this).index()].head_logo
                var str = `<div class="friend-infomation">
                <div class="friend-head">
                    <div class="friend-logo">
                        <img src="http://118.24.25.7/chat_api/${fridentlogo}">
                    </div>
                    <div class="name">
                        <p>${nick}</p>
                        <span>${id}</span>
                    </div>
                    
                </div>
               
                <div class="friend-footer">
                    <div class="send">
                        发消息
                    </div>
                    <div class="delete">
                        删除好友
                    </div>
                </div>
            </div>`
                $main.html(str)

            })
            console.log(res.data)
        }
    },

})
//删除好友
$main.on("click", ".delete", function () {
    // console.log(11)
    var deleteData = {
        sign_str: userData.sign_str,
        user_id: userData.user_id,
        friend_id: id
    }
    console.log(deleteData)
    $.ajax({
        type: "post",
        url: "http://118.24.25.7/chat_api/interface/removeFriend.php",
        data: deleteData,
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                var str = `
                <div class="tooltips">
                    <div class="tooltips-title">
                        已成功删除对方。
                    </div>
                </div>`
                $box.append(str)
                var $tooltips = $(".tooltips")
                time = setTimeout(function () {
                    $tooltips.css("display", "none")
                    clearTimeout(time)
                }, 1200)


            }
        }
    })
})

//打开消息窗口
$main.on("click", ".send", function () {
    // console.log(11)
    var str = `
        <div class="msg">
        <div class="msg-title">
            <span>${nick}</span>
        </div>
        <div class="msg-content">
            
        </div>
        <div class="msg-footer">
            <div class="lable">
                <div class="functional">
                    <div class="iconfont icon-xiaolian"></div>
                    <div class="iconfont icon-cloud-folder"></div>
                    <div class="iconfont icon-jianqie"></div>
                    <div class="iconfont icon-xinxi"></div>
                </div>
                <div class="facility">
                    <div class="iconfont icon-dianhua"></div>
                    <div class="iconfont icon-shipin"></div>
                </div>
            </div>
            <div class="textarea">
                <textarea autofocus>

                </textarea>
            </div>
            <div class="forword">发送(S)</div>
        </div>
    </div>
        `
    $main.html(str)
    console.log(11111,$(".msg-content")[0].scrollHeight)
    getMessage()


})
//获取消息历史记录
var $rdlen = 0;
function getMessage() {
    // var getMessages={
    //     sign_str: userData.sign_str,
    //     user_id: userData.user_id
    // }
    var getChatHistory = {
        sign_str: userData.sign_str,
        user_id: userData.user_id,
        friend_id: id
    }
    $.ajax({
        type: "get",
        timeout: 1500,
        url: "http://118.24.25.7/chat_api/interface/getChatHistory.php",
        data: getChatHistory,
        dataType: "json",
        success: function (res) {
            if ($rdlen == res.data.length) {
                return
            } else {
                $rdlen = res.data.length

            }
            console.log(res.data)

            if (res.code == 0) {
                $(".msg-content").html("")
                for (var i = 0; i < res.data.length; i++) {


                    if (res.data[i].user_id == id) {
                        var str = `
                        <div class="xiaoxi"><span>${res.data[i].message}</span></div>
            `
                        $(".msg-content").append(str)
                    }
                    if (res.data[i].user_id == getChatHistory.user_id) {
                        var str = `
                        <div class="forword-ziji"><span>${res.data[i].message}</span></div>
            `
                        $(".msg-content").append(str)
                    }
                    $(".msg-content").scrollTop($(".msg-content")[0].scrollHeight)

                }


            }

        },
        complete: function () {
            getMessage()
        }
    })

}



//发送消息

$main.on("click", ".forword", function () {
    var $textarea = $("textarea")
    var message = $textarea.val()
    var sendMessage = {
        sign_str: userData.sign_str,
        user_id: userData.user_id,
        receive_user_id: id,
        message: message
    }
    console.log(sendMessage)
    $.ajax({
        type: "post",
        url: "http://118.24.25.7/chat_api/interface/sendMessage.php",
        data: sendMessage,
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                console.log(res.data)
                var str = `
                <div class="forword-ziji"><span>${sendMessage.message}</span></div>
                `
                $(".msg-content").append(str)

                $textarea.val("")
            }
        }
    })
})



//退出登录


var $tuichu = $(".set")
$tuichu.on("click", ".icon-tuichu", function () {
    var logout = {
        sign_str: userData.sign_str,
        user_id: userData.user_id
    }

    $.ajax({
        type: "post",
        url: "http://118.24.25.7/chat_api/interface/logout.php",
        data: logout,
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                var str = `
                <div class="tooltips">
                    <div class="tooltips-title">
                        你已退出登录。
                    </div>
                </div>`
                $box.append(str)
                var $tooltips = $(".tooltips")
                time = setTimeout(function () {
                    $tooltips.css("display", "none")
                    location.href = "login.html"
                    clearTimeout(time)
                }, 1200)

            }
        }
    })
})